package cn.itcast.bos.web.action.system;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

    @Autowired
    private UserService userService;

    //用户登录
    @Action(value = "user_login",results = {@Result(name = "success",type = "redirect",location = "index.html"),
                                        @Result(name = "login",type = "redirect",location = "login.html") })
    public String login () {
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //根据model获取用户名和密码封装成令牌
        UsernamePasswordToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
        //将令牌使用subject对象发送到认证服务端，如果登录失败会有异常，  try/catch
        try {
            subject.login(token);
            return SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return LOGIN;
        }
    }

    //用户登出user_loginOut.action
    @Action(value = "user_loginOut",results = {@Result(name = "login",type = "redirect",location = "login.html") })
    public String loginOut(){
        //基于shiro的subject登出
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return LOGIN;
    }

    //查询用户列表user_list.action
    @Action(value = "user_list",results = {@Result(name = "success",type = "json") })
    public String findList(){
        List<User> list = userService.findAll();
        ActionContext.getContext().getValueStack().push(list);
        return SUCCESS;
    }

    //保存用户，user_add.action
    @Action(value = "user_add",results = {@Result(name = "success",type = "redirect",location = "/pages/system/userindex.html") })
    public String userAdd(){
        userService.save(model);
        return SUCCESS;
    }


}
